<template>
  <el-dialog
    :model-value="addDialogVisible"
    title="基于等值分析的损害实物量化结果"
    width="840px"
    @close="closeDialog"
  >
    <div>
      <el-table :data="props.results" :border="true" :show-header="false">
        <el-table-column type="index" width="80" />
        <el-table-column prop="name" label="name" />
        <el-table-column prop="value" label="value" />
      </el-table>
    </div>
    <div class="text-right">
      <el-button type="primary" @click="exportTxt"> 导出 </el-button>
      <el-button @click="copyClick">复制</el-button>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'

interface IResult {
  name: string
  value: string
}

const props = defineProps<{
  addDialogVisible: boolean
  results: IResult[]
}>()

// 定义emit事件
const emit = defineEmits({
  closeDialog: null
})

const closeDialog = function () {
  emit('closeDialog')
}

const copyClick = function () {
  let message: string = ''
  props.results.forEach((element) => {
    message += element.name + '  ' + element.value + '\n'
  })
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard
      .writeText(message)
      .then(() => {
        ElMessage({
          message: '复制成功',
          type: 'success'
        })
      })
      .catch(() => {
        ElMessage({
          message: '复制失败 ',
          type: 'error'
        })
      })
  } else {
    // 创建text area
    const textArea = document.createElement('textarea')
    textArea.value = message
    // 使text area不在viewport，同时设置不可见
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()
    new Promise((resolve, reject) => {
      // 执行复制命令并移除文本框
      document.execCommand('copy') ? resolve(null) : reject(new Error('出错了'))
      textArea.remove()
    }).then(
      () => {
        ElMessage({
          message: '复制成功',
          type: 'success'
        })
      },
      () => {
        ElMessage({
          message: '复制失败 ',
          type: 'error'
        })
      }
    )
  }
}

const exportTxt = function () {
  let message: string = ''
  props.results.forEach((element) => {
    message += element.name + '  ' + element.value + '\n'
  })
  const blob = new Blob([message], { type: 'text/plain;charset=utf-8' })
  saveAs(blob, '计算结果.txt')
}
</script>
<style lang="scss" scoped></style>
<style lang="scss"></style>
